package cn.zhxu.toys.oss;

import java.io.*;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.Random;

import com.aliyun.oss.common.auth.DefaultCredentialProvider;
import com.aliyun.oss.model.OSSObject;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;

import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;

/**
 * 阿里云对象存储管理器
 * @author Troy.Zhou
 */
public class AliyunOssManager extends AbstractOssManager implements InitializingBean, DisposableBean {

	
	private String accessKeyId;
	
	private String accessKeySecret;
	
	private String bucketName;
	
	private OSSClient client;
	
	
	@Override
	public void afterPropertiesSet() {
		client = new OSSClient(endpoint, new DefaultCredentialProvider(accessKeyId, accessKeySecret), null);
	}

	@Override
	public InputStream access(String key) {
		OSSObject ossObject = client.getObject(bucketName, key);
		return ossObject.getObjectContent();
	}

	@Override
	public String upload(String fileName, String key, String contentType, String extension, InputStream inputStream) {
		try {
			long fileSize = inputStream.available();
			if(fileSize > maxSize) {
				inputStream.close();
				throw new RuntimeException("上传的文件过大：" + fileSize + "，最大只允许：" + maxSize);
			}
			ObjectMetadata metadata = new ObjectMetadata();
			metadata.setContentLength(inputStream.available());
			metadata.setCacheControl("no-cache");
			metadata.setHeader("Pragma", "no-cache");
			metadata.setContentEncoding("utf-8");
			if (fileName == null) {
				fileName = System.currentTimeMillis()
						+ new Random().nextInt() + extension;
			} else {
				fileName += extension;
			}
			if (contentType != null) {
				metadata.setContentType(contentType);
			}
			metadata.setContentDisposition("filename/filesize=" + fileName + "/" + fileSize + "Byte.");
			if (!key.endsWith("/")) {
				key += "/";
			}
			String fileKey = key + fileName;
			client.putObject(bucketName, fileKey, inputStream, metadata);
			return resolveFileAccessUrl(fileKey);
		} catch (Exception e) {
			throw new RuntimeException("上传出现异常：", e);
		}
	}

	@Override
	public boolean delete(String fileUrl) {
		String fileKey = resolveFileKey(fileUrl);
		if (fileKey != null) {
			try {
				String decodedKey = URLDecoder.decode(fileKey, StandardCharsets.UTF_8.name());
				client.deleteObject(bucketName, decodedKey);
				return true;
			} catch (UnsupportedEncodingException e) {
				throw new RuntimeException(e);
			}
		}
		return false;
	}

	@Override
	public void destroy() {
		client.shutdown();
	}

	@Override
	protected String getBaseAccessUrl(String protocol, String host) {
		return protocol + bucketName + "." + host + "/";
	}
	
	
	public String getAccessKeyId() {
		return accessKeyId;
	}

	public void setAccessKeyId(String accessKeyId) {
		this.accessKeyId = accessKeyId;
	}

	public String getAccessKeySecret() {
		return accessKeySecret;
	}

	public void setAccessKeySecret(String accessKeySecret) {
		this.accessKeySecret = accessKeySecret;
	}

	public String getBucketName() {
		return bucketName;
	}

	public void setBucketName(String bucketName) {
		this.bucketName = bucketName;
	}

}
